<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="交易订单" prop="tradeOrderNo" label-width="88px">
            <el-input v-model="queryParams.tradeOrderNo" placeholder="请输入交易订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="商户名称" prop="merchantName">
            <el-input v-model="queryParams.merchantName" placeholder="请输入商户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="商铺名称" prop="shopName">
            <el-input v-model="queryParams.shopName" placeholder="请输入商铺名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单金额" prop="amount">
            <el-input v-model="queryParams.amount" placeholder="请输入订单金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收银账号" prop="cashier">
            <el-input v-model="queryParams.cashier" placeholder="请输入收银员" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 240px">
              <el-option v-for="dict in biz_pay_order_state" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['retail:payOrder:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="payOrderList" class="tableEmpty">
        <el-table-column label="订单号/渠道订单" align="center" prop="orderNo" width="200px">
          <template #default="scope">
            <el-link type="primary" :underline="true" @click="handleView(scope.row)">{{ scope.row.orderNo }}</el-link>
            <el-link type="info" :underline="true">{{ scope.row.tradeOrderNo }}</el-link>
          </template>
          <template v-slot:header>
            订单号/渠道订单
            <el-popover placement="top-start"  effect="dark" :width="260" trigger="hover" content="点击订单号查看付款凭证">
              <template #reference>
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <!--<el-table-column label="交易订单" align="center" prop="tradeOrderNo" />-->
        <el-table-column label="商户名称" align="center" prop="merchantName" />
        <el-table-column label="店铺/销售员" align="center" prop="shopName">
          <template #default="scope">
            {{ scope.row.shopName?scope.row.shopName:scope.row.sellerName }}
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" prop="amount">
          <template #default="scope">
            {{ scope.row.amount/100 }}
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="actualAmount">
          <template #default="scope">
            {{ scope.row.actualAmount/100 }}
          </template>
        </el-table-column>
        <el-table-column label="手续费" align="center" prop="fee">
          <template #default="scope">
            {{ scope.row.fee/100 }}
          </template>
        </el-table-column>
        <el-table-column label="收银员" align="center" prop="cashier" />
        <el-table-column label="付款人" align="center" prop="purchaser" />
        <!--<el-table-column label="店铺收益" align="center" prop="shopProfit" />
        <el-table-column label="商铺收益" align="center" prop="merchantProfit" />-->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="biz_pay_order_state" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="回调" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="回调" placement="top" v-if="scope.row.status==1">
              <el-button link type="primary" icon="Upload" @click="handleNotify(scope.row)" v-hasPermi="['retail:payOrder:view']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
          <!--<el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" v-hasPermi="['retail:payOrder:view']"></el-button>
            </el-tooltip>-->
            <el-tooltip content="申诉" placement="top" v-if="scope.row.status==8">
              <el-button link type="success" icon="Help" @click="handleAppeal(scope.row)" v-hasPermi="['retail:payOrder:view']"></el-button>
            </el-tooltip>
            <el-tooltip content="冲正" placement="top" v-if="scope.row.status==1 && scope.row.accountingMode==1">
              <el-button link type="success" icon="Guide" @click="handleReverse(scope.row)" v-hasPermi="['retail:payOrder:view']"></el-button>
            </el-tooltip>
            <!--<el-tooltip content="查单" placement="top" v-if="scope.row.status==1">
              <el-button link type="primary" icon="Search" @click="handleAsk(scope.row)" v-hasPermi="['retail:payOrder:view']"></el-button>
            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <el-dialog :title="securityDialog.title" v-model="securityDialog.visible" :show-close="false" :close-on-click-modal="false" width="500px" append-to-body>
      <el-card>
        <span>
          谷歌验证码:
          <el-input v-model="googleAuthCode" placeholder="请输入谷歌驗證碼" clearable style="width: 240px" />
        </span>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="doNotify" v-if="securityDialogType=='notify'">回调提交</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="doReverse" v-if="securityDialogType=='reverse'">冲正提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="appealDialog.title" v-model="appealDialog.visible" width="500px" append-to-body>
      <el-card>
        <el-row :gutter="10" class="mb8">
          <el-col :span="24" :xs="24">
            <el-descriptions
              class="margin-top"
              :column="1"
              border
            >
              <el-descriptions-item label-class-name="my-label">
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <user />
                    </el-icon>
                    申诉视频
                  </div>
                </template>
                <el-link :href="appealInfo.videoUrl" target="_blank">播放视频</el-link>
                {{appealInfo.videoUrl}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <iphone />
                    </el-icon>
                    申诉图片
                  </div>
                </template>
                <el-image :src="appealInfo.imageUrl" />
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <iphone />
                    </el-icon>
                    谷歌验证码
                  </div>
                </template>
                <el-input v-model="googleAuthCode" placeholder="请输入谷歌驗證碼" clearable style="width: 240px" />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="doAppeal" v-if="selectedRow.status==8">确认未收款，冲正</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-card>
        <el-row :gutter="10" class="mb8">
          <el-col :span="24" :xs="24">
            <el-descriptions
              class="margin-top"
              :column="1"
              border
            >
              <el-descriptions-item label-class-name="my-label">
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <user />
                    </el-icon>
                    付款人
                  </div>
                </template>
                {{ selectedRow.purchaser }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <iphone />
                    </el-icon>
                    付款凭证
                  </div>
                </template>
                <el-image :src="selectedRow.paymentVoucher" />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleAsk" v-if="selectedRow.status==1">机器人询单</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayOrder" lang="ts">
import { sendMsgForAsk } from '@/api/retail/robot';
import { listPayOrder, reversePayOrder, notifyPayOrder,appealPayOrder } from '@/api/retail/payOrder';
import { PayOrderVO, PayOrderQuery, PayOrderForm } from '@/api/retail/payOrder/types';
import {Iphone, QuestionFilled} from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { biz_pay_order_state } = toRefs<any>(proxy?.useDict('biz_pay_order_state'));

const payOrderList = ref<PayOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const securityDialogType = ref('');

const queryFormRef = ref<ElFormInstance>();
const payOrderFormRef = ref<ElFormInstance>();
const googleAuthCode = ref('');
const appealInfo = ref({"videoUrl":"","imageUrl":""});
const securityDialog = reactive<DialogOption>({
  visible: false,
  title: '订单回調',
});
const appealDialog = reactive<DialogOption>({
  visible: false,
  title: '订单申诉'
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: '订单详情'
});

const initFormData: PayOrderForm = {
  id: undefined,
  orderNo: undefined,
  merchant: undefined,
  merchantName: undefined,
  shop: undefined,
  shopName: undefined,
  purchaser: undefined,
  amount: undefined,
  actualAmount: undefined,
  fee: undefined,
  cashier: undefined,
  cashBoxLink: undefined,
  shopProfit: undefined,
  merchantProfit: undefined,
  status: undefined,
  createTime: '',
  expireTime: ''
}
const data = reactive<PageData<PayOrderForm, PayOrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    merchant: undefined,
    merchantName: undefined,
    shop: undefined,
    shopName: undefined,
    purchaser: undefined,
    amount: undefined,
    actualAmount: undefined,
    fee: undefined,
    cashier: undefined,
    cashBoxLink: undefined,
    shopProfit: undefined,
    merchantProfit: undefined,
    status: undefined,
    createTime: '',
    expireTime: '',
    params: {
    }
  },
  rules: {
  }
});
const selectedRow = ref<{id:string|number|undefined,orderNo:string|undefined,
  paymentVoucher:string|undefined, purchaser: string|undefined,status:string|number|undefined}>({
  id: 0,
  orderNo: '',
  paymentVoucher: '',
  purchaser: '',
  status: 0
});
const { queryParams, form, rules } = toRefs(data);
const videoPlayer = ref(null);

const playVideo = () => {
  if(videoPlayer.value) {
    (videoPlayer as any).play();
  }
};
/** 查询支付订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayOrder(queryParams.value);
  payOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  // reset();
  selectedRow.value.paymentVoucher = '';
  selectedRow.value.purchaser = '';
  selectedRow.value.orderNo = '';
  selectedRow.value.id = 0;
  selectedRow.value.status = 0;
  //Object.assign(selectedRow, initFormData);
  dialog.visible = false;
  securityDialog.visible = false;
  appealDialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  payOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('retail/payOrder/export', {
    ...queryParams.value
  }, `payOrder_${new Date().getTime()}.xlsx`)
}

/** 查看详情 */
const handleView = (row?: PayOrderVO) => {
  dialog.visible = true;
  selectedRow.value.id = row?.id;
  selectedRow.value.orderNo = row?.orderNo;
  selectedRow.value.purchaser = row?.purchaser;
  selectedRow.value.paymentVoucher = row?.paymentVoucher;
  selectedRow.value.status = row?.status;
  //Object.assign(selectedRow, row);
}

const handleAppeal = (row?: PayOrderVO) => {
  appealDialog.visible = true;
  appealDialog.title = "订单申诉";
  selectedRow.value.id = row?.id;
  selectedRow.value.orderNo = row?.orderNo;
  selectedRow.value.status = row?.status;
  if(row?.appealInfo) {
    let info = JSON.parse(row.appealInfo);
    appealInfo.value.imageUrl = info.imageUrl;
    appealInfo.value.videoUrl = info.videoUrl;
  }
}
/** 冲正 **/
const handleReverse = async (row?: PayOrderVO) => {
  securityDialog.visible = true;
  securityDialog.title = "订单冲正";
  securityDialogType.value = "reverse";
  selectedRow.value.id = row?.id;
  selectedRow.value.orderNo = row?.orderNo;
  selectedRow.value.status = row?.status;
}

const doAppeal = async () => {
  if(!googleAuthCode.value) {
    proxy?.$modal.msgWarning("请输入谷歌验证码");
    return;
  }
  buttonLoading.value = true;
  const res = await appealPayOrder(selectedRow?.value.id, googleAuthCode.value).finally(()=>{
    buttonLoading.value = false;
  });

  if (res.code == 200) {
    proxy?.$modal.msgSuccess("订单申诉处理成功");
    appealDialog.visible = false;
    googleAuthCode.value = '';
    await getList();
  } else {
    proxy?.$modal.msgError("订单申诉处理失败:" + res.msg);
  }
}
const doReverse = async () => {
  if(!googleAuthCode.value) {
    proxy?.$modal.msgWarning("请输入谷歌验证码");
    return;
  }
  buttonLoading.value = true;
  const res = await reversePayOrder(selectedRow?.value.id, googleAuthCode.value).finally(()=>{
    buttonLoading.value = false;
  });

  if (res.code == 200) {
    proxy?.$modal.msgSuccess("订单冲正成功");
    securityDialog.visible = false;
    googleAuthCode.value = '';
    await getList();
  } else {
    proxy?.$modal.msgError("订单冲正失败:" + res.msg);
  }
}

/** 回调 */
const handleNotify = async (row?: PayOrderVO) => {
  securityDialog.visible = true;
  securityDialog.title = "订单回调";
  securityDialogType.value = "notify";
  selectedRow.value.id = row?.id;
  selectedRow.value.orderNo = row?.orderNo;
  selectedRow.value.status = row?.status;
}
const doNotify = async () => {
  if(!googleAuthCode.value) {
    proxy?.$modal.msgWarning("请输入谷歌验证码");
    return;
  }
  buttonLoading.value = true;
  const res = await notifyPayOrder(selectedRow?.value.id, googleAuthCode.value).finally(()=>{
    buttonLoading.value = false;
  });

  if (res.code == 200) {
    proxy?.$modal.msgSuccess("强制回调成功");
    securityDialog.visible = false;
    googleAuthCode.value = '';
    await getList();
  } else {
    proxy?.$modal.msgError("强制回调失败:" + res.msg);
  }
}
/** 询单 */
const handleAsk = async () => {
  await proxy?.$modal.confirm('确认要询问订单（' + selectedRow?.value.orderNo + '）的付款情况吗?');
  buttonLoading.value = true;
  const res = await sendMsgForAsk(selectedRow?.value.id);
  buttonLoading.value = false;
  if(res.code==200) {
    proxy?.$modal.msgSuccess("发送询单信息成功");
  }else {
    proxy?.$modal.msgError("发送询单信息失败:"+res.msg);
  }
}

onMounted(() => {
  getList();
});
</script>
<style scoped>
:deep(.my-label) {
  width: 120px; /* 自定义宽度 */
  background: var(--el-color-success-light-9) !important;
}
</style>
